import matplotlib.pyplot as plt
from matplotlib import gridspec

from src.EventBus import EventManager, Event


class View:
    def __init__(self):
        self.ax0 = None
        self.ax1 = None
        self.fig = None
        self.gs = None

    @staticmethod
    def handle_close(evt):
        EventManager.emit(Event(Event.ON_APPLICATION_CLOSE))

    def pre_draw(self):
        self.fig = plt.figure(figsize=(9, 5))
        self.fig.canvas.mpl_connect('close_event', View.handle_close)

        self.gs = gridspec.GridSpec(2, 2,width_ratios=[1, 1], height_ratios=[1, 1])

    def draw(self, event):

        try:
            df_rank = event.dict['data'].df_result
            df_mem = event.dict['data'].df_tail

            print(df_rank)

            plt.clf()

            self.draw_rank(df_rank)
            self.draw_mem(df_mem)

            plt.pause(0.01)
        except:
            pass

    @staticmethod
    def show():
        plt.show()

    def draw_rank(self, df):
        self.ax0 = self.fig.add_subplot(self.gs[0, :])
        for index in df.columns:
            self.ax0.plot(df[index], label=index)
        plt.legend()

    def draw_mem(self, df):
        self.ax1 = self.fig.add_subplot(self.gs[1, :])
        for index in df.columns:
            self.ax1.plot(df[index].astype(int).tolist(), label=index)
        plt.legend()
        # plt.axhspan(80000, 80500, facecolor='#2ca02c', alpha=0.5)
